#!/bin/sh

if [ -e /usr/share/debconf/confmodule ]; then
  . /usr/share/debconf/confmodule

  OPTS="--config config.json"

  db_get pisugar-server/model
  OPTS="$OPTS --model '$RET'"

  db_get pisugar-server/address
  ADDR="$RET"

  db_get pisugar-server/web
  if test "x$RET" = "xtrue"; then
    OPTS="$OPTS --web /usr/share/pisugar-server/web --http $ADDR:8421 --ws $ADDR:8422 "
  fi

  db_get pisugar-server/tcp
  if test "x$RET" = "xtrue"; then
    OPTS="$OPTS --tcp $ADDR:8423"
  fi

  db_get pisugar-server/uds
  if test "x$RET" = "xtrue"; then
    OPTS="$OPTS --uds /tmp/pisugar-server.sock"
  fi

  echo "OPTS=$OPTS" >/etc/default/pisugar-server

  if which jq > /dev/null; then
    db_input high pisugar-server/auth-username || true
    db_input high pisugar-server/auth-password || true
    db_go

    db_get pisugar-server/auth-username
    username="$RET"
    db_get pisugar-server/auth-password
    password="$RET"
    db_set pisugar-server/auth-password ""

    config=$(cat /etc/pisugar-server/config.json)
    if test "x$username" != "x" || test "x$password" != "x"; then
      echo "$config" |\
        jq ".auth_user=\"$username\"" |\
        jq ".auth_password=\"$password\"" > /etc/pisugar-server/config.json
    fi

    db_input high pisugar-server/auth-note
    db_go

  else
    db_input high pisugar-server/auth-default
    db_go
  fi
fi

# Enable i2c
if which raspi-config > /dev/null 2>&1; then
  raspi-config nonint do_i2c 0 || true
fi

deb-systemd-helper unmask pisugar-server.service >/dev/null || true
if deb-systemd-helper --quiet was-enabled pisugar-server.service; then
  deb-systemd-helper enable pisugar-server.service >/dev/null || true
  deb-systemd-invoke start pisugar-server.service || true
else
  deb-systemd-helper update-state pisugar-server.service >/dev/null || true
fi
